﻿
namespace CoProject.Repository
{
    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Linq;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.Composition;
    using CoProjectModel;
    using IdeaBlade.Core;
    using IdeaBlade.EntityModel;
    using IdeaBlade.Application.Framework.Core.Persistence;
    using Caliburn.Micro;
    using Caliburn.Micro.Extensions;

    /// <summary>
    /// This is an IResults version of a Repository.
    /// In essence this is re-write of LoadDataResult.cs from the original CoProject.
    /// However, when using DevforceCaliburn library an INotifyCompleted is
    /// the preferred solution.
    /// </summary>
    [Export(typeof(IToDoItemRepository))]
    public class ToDoItemRepository : IToDoItemRepository, IResult
    {
        private IEntityManagerProvider<CoProjectEntities> EntityManagerProvider { get; set; }
        private CoProjectEntities Manager { get { return EntityManagerProvider.Manager; } }
        private int _id;
        private string mode = "";

        [ImportingConstructor]
        public ToDoItemRepository(IEntityManagerProvider<CoProjectEntities> entityManagerProvider)
        {
            EntityManagerProvider = entityManagerProvider;
        }

        public void FindToDoItemByID(int ID)
        {
            _id = ID;
            mode = "Query";
        }

        public void Save()
        {
            mode = "Save";
        }

        public ToDoItem MyResults { get; set; }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };

        public void Execute(ActionExecutionContext context)
        {
            if (mode == "Query")
            {
                var q = Manager.ToDoItems.Where(c => c.ToDoItemID == _id);
                var op = q.ExecuteAsync((a) =>
                {
                    if (a.CompletedSuccessfully)
                    {
                        MyResults = (a.Results as IdeaBlade.EntityModel.QueryResultsList<ToDoItem>).FirstOrDefault();
                        Completed(this, new ResultCompletionEventArgs());
                    }
                });
            }
            else
                if (mode == "Save")
                {
                    EntitySaveOperation so = Manager.SaveChangesAsync((s) =>
                    {
                        if (s.CompletedSuccessfully)
                        {
                            var a = s.Entities;
                            Completed(this, new ResultCompletionEventArgs());
                        }
                    });
                }
                else
                {
                    throw new Exception("Incorrect Mode");
                }

            mode = "";
        }
    }
}
